<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="today" v-if="todayPurchaseOffer">今日报价</el-menu-item>
      <el-menu-item index="create" v-if="myChargePurchaseOffer">我创建的</el-menu-item>
      <el-menu-item index="all" v-if="allPurchaseOffer">全部报价</el-menu-item>
      <el-menu-item index="goods" v-if="purchaseOfferGoods">商品管理</el-menu-item>
    </el-menu>
    <el-menu v-if="listQuery.tab == 'goods'" :default-active="listQuery.tab2" class="el-menu-demo" mode="horizontal" @select="handleSelect2">
      <el-menu-item index="charge">我负责的</el-menu-item>
      <el-menu-item index="all">全部</el-menu-item>
    </el-menu>

    <!--数据列表-->
    <div class="table-container">
      <vxe-grid ref='xGrid' v-bind="gridOptions" size="mini" :loading="listLoading"  @checkbox-change="checkboxChange" @checkbox-all="selectAllCheckboxChange">
        <template #form>
          <!--搜索-->
          <div>
            <div style="background: #f5f7fa;padding:15px 15px 0 15px;border:1px solid #EBEEF5;border-bottom:0.5px solid #EBEEF5;">
              <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
                <el-form-item label="线上商品名称" v-if="listQuery.tab == 'goods'  ">
                  <el-input clearable v-model="listQuery.goodsName"  placeholder="请选择" >
                  </el-input>
                </el-form-item>
                <el-form-item label="牌号" >
                  <el-select
                    v-model="listQuery.goodsSnId"
                    filterable
                    :remote-method="getMaterialsList"
                    clearable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :loading="loading"
                  >
                    <el-option v-for='item in materialsList' :key ='item.goodsSnId' :value="item.goodsSnId" :label="item.categoryName+'/'+item.goodsSn">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="品名："  v-if="listQuery.tab != 'goods' " >
                  <el-input clearable v-model="listQuery.categoryName"></el-input>
                </el-form-item>
                <el-form-item label="供货方：" v-if="(listQuery.tab == 'all' || listQuery.tab == 'goods')&&type=='todayPrice'">
                  <el-select v-model="listQuery.fromCompany" filterable placeholder="请选择" clearable @change="handleWarehouseId">
                    <el-option
                      v-for="item in fromCompanyList"
                      :key="item.fromCompanyId"
                      :label="item.fromCompanyName"
                      :value="item.fromCompanyName">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="发货仓库：" v-if="listQuery.tab == 'goods'&&type=='todayPrice'">
                  <el-select v-model="listQuery.warehouseName" filterable placeholder="请选择" clearable >
                    <el-option
                      v-for="(item,index) in warehouseLists"
                      :key="index"
                      :label="item.warehouseName"
                      :value="item.warehouseName">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="报价时间：" v-if="listQuery.tab != 'today'&&listQuery.tab != 'goods'">
                  <el-date-picker
                    v-model="listQuery.priceDate"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    format="yyyy 年 MM 月 dd 日"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item :label="listQuery.tab == 'all'?'采购员':'负责人'" v-if="listQuery.tab != 'create' && listQuery.tab != 'goods'">
                  <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
                    <el-option v-for="item in chargeDataList" :key="item.userId" :value="item.userId" :label="item.userName">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label='负责人' v-if="listQuery.tab == 'goods'&& listQuery.tab2 == 'all'">
                  <el-select v-model="listQuery.chargeUserId" filterable placeholder="请选择" clearable>
                    <el-option v-for="item in chargeDataList" :key="item.userId" :value="item.userId" :label="item.userName">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="是否允许下单：" v-if="listQuery.tab == 'goods' && type == 'todayPrice'">
                  <el-select v-model="listQuery.isEnableOrder "  placeholder="请选择" clearable>
                    <el-option key="1" label="正常下单" value="1"></el-option>
                    <el-option key="0" label="禁止下单" value="0"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button
                    @click="handleSearchList()"
                    type="primary">
                    查询
                  </el-button>
                  <el-button
                    v-if="listQuery.tab == 'create'"
                    @click="toTemp('create')"
                    type="primary">
                    批量复制报价
                  </el-button>
                  <el-button
                    v-if="listQuery.tab == 'goods'"
                    @click="toTemp('goods')"
                    type="primary">
                    批量报价
                  </el-button>
                  <el-button @click="changeMoreType(1)" type="success" :loading="btnloading1" v-if="listQuery.tab == 'goods' && type == 'todayPrice'">
                    批量允许下单
                  </el-button>
                  <el-button @click="changeMoreType(0)" type="danger" :loading="btnloading2" v-if="listQuery.tab == 'goods' && type == 'todayPrice'">
                    批量禁止下单
                  </el-button>
                  <!-- <el-button
                    v-if="listQuery.tab == 'goods'"
                    @click="showAddGoods()"
                    type="primary">
                    新增商品
                  </el-button> -->
                </el-form-item>
              </el-form>
            </div>
          </div>
        </template>
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container" style="float:right;">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count">
              </el-pagination>
            </div>
          </div>
        </template>
        <template #toolbar_buttons>
          <el-radio-group v-model="type" size="small"  @change="changeType" v-if="listQuery.tab =='goods'">
             <el-radio-button label="all">全部({{ allCount }})</el-radio-button>
            <el-radio-button label="todayPrice">今日已报价({{ todayPriceCount }})</el-radio-button>
            <el-radio-button label="todayUnPrice">今日未报价({{ todayUnPriceCount }})</el-radio-button>
            <!-- <el-radio-button label="normal">线上商品({{ normalCount }})</el-radio-button>
            <el-radio-button label="normalUnPrice">线上商品未报价({{ normalUnPriceCount }})</el-radio-button> -->
            </el-radio-group>
        </template>
        <template #num1_default="{ row, rowIndex }">
          <!-- /{{ row.brandName }} -->
          <span>{{ row.categoryName }}/{{ row.goodsSn }}</span>
        </template>
        <template #num2_default="{ row, rowIndex }">
          <span>{{row.expectSendDate}}</span>
          <span style="background: red;color:#fff;padding:0 5px;border-radius: 5px" v-if="row.urgentType == '必须'">必须</span>
          <span style="background:#ff6600;color:#fff;padding:0 5px;border-radius: 5px" v-if="row.urgentType == '可延1-2天'">1-2天</span>
          <span style="background:#ff9900;color:#fff;padding:0 5px;border-radius: 5px" v-if="row.urgentType == '可延1-2周'">1-2周</span>
          <span style="background:#0099ff;color:#fff;padding:0 5px;border-radius: 5px" v-if="row.urgentType == '等客户通知'">等待</span>
        </template>

        <template #num3_default="{ row, rowIndex }">
          <el-button style="margin-right:10px;" type="text" v-if="(listQuery.tab=='create'&& row.createTimeSecond *1000 > cutTime)||listQuery.tab=='all' " size="small" @click="editPrice(row)">修改</el-button>
          <el-button style="margin-right:10px;" type="text" v-if="listQuery.tab=='create'||listQuery.tab=='all' " size="small" @click="showLoger(row)">日志</el-button>
          <el-button style="margin-right:10px;" type="text" v-if="listQuery.tab=='goods'&&(type=='todayPrice' || type=='all')" size="small" @click="showAddGoods(row)">编辑报价</el-button>
          <el-button style="margin-right:10px;" type="text" v-if="listQuery.tab=='goods'&&(type=='todayUnPrice' || type=='all')" size="small" @click="editTempOffer(row)">生成报价</el-button>
          <el-button
            v-if="listQuery.tab=='goods'&& type=='todayPrice'"
            type="text"
            style="margin-right:10px;"
            size="small"
            @click="changeOrderType(row,  'isEnableOrder')"
          >{{ row.isEnableOrder == 1 ? '禁止下单' : '允许下单' }}</el-button>
          <!-- <el-button style="margin-right:10px;" type="text" v-if="listQuery.tab=='goods'" size="small" @click="editSort(row)">修改排序</el-button> -->
        </template>
        <template #num4_default="{ row, rowIndex }">
          <span>{{ row.createdTime | formatTime }}</span>
        </template>

      </vxe-grid>
    </div>

    <el-dialog
    :close-on-click-modal="false"
    title="修改"
    :visible.sync="dialogVisible"
    :beforeClose="handleClose"
    width="400px">
    <el-form size="mini" :model="sendForm" label-width="120px"  ref="sendForm" :rules="rules">
        <el-form-item label="价格：" prop="purchasePrice">
          <el-input style="width:150px" v-model="sendForm.purchasePrice" clearable></el-input>
        </el-form-item>
        <el-form-item label="采购成本价：" prop="costPrice">
          <el-input
            style="width: 150px"
            v-model="sendForm.costPrice"
            clearable
          ></el-input>
          <div v-if="sendForm.purchasePrice > 0 && sendForm.costPrice > 0" style="color: red;font-size:12px;">
            采购吨毛利：{{ sendForm.purchasePrice | fifterNumber(sendForm.costPrice) }}
          </div>
        </el-form-item>
        <el-form-item label="线上平台价：" prop="onlinePrice" v-if="sendForm.sendTypes=='自提'">
          <el-input
            style="width: 150px"
            v-model="sendForm.onlinePrice"
            clearable
          ></el-input>
          <div
            style="color: red;font-size:12px;">
            请注意最低毛利为{{ minProfit }}元/吨
          </div>
        </el-form-item>
        <el-form-item label="有效小时数：" v-if="sendForm.onlinePrice>0" prop="validHours">
          <el-input
            style="width: 150px"
            v-model="sendForm.validHours"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="可售库存量(吨)："  prop="stockNum">
            <el-input style="width:150px" v-model="sendForm.stockNum" clearable></el-input>
        </el-form-item>
        <el-form-item label="发货日期："  prop="sendDate">
            <el-date-picker
              :picker-options="isDisabled"
              style="width:150px"
              v-model="sendForm.sendDate"
              type="date"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 认</el-button>
    </span>
    </el-dialog>

    <!-- <el-dialog
    :close-on-click-modal="false"
    title="修改商品排序"
    :visible.sync="dialogVisible2"
    :beforeClose= 'handleClose2'
    width="400px">
    <el-form size="mini" :model="sendForm2" label-width="100px"  ref="sendForm2" :rules="rules2">
        <el-form-item label="商品排序值" prop="inquirySort">
          <el-input style="width:150px" v-model="sendForm2.inquirySort"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading">确 认</el-button>
      </span>
    </el-dialog> -->
    <!--新增采购报价-->
    <addPurchaseOffer @update="handleSearchList" ref="addPurchaseOffer"></addPurchaseOffer>

    <!-- 编辑新增商品 -->
    <!-- <addPumsGoods @update="handleSearchList" ref="addPumsGoods"></addPumsGoods> -->

    <!-- 生成报价 -->
    <addTempOffer ref="addTempOffer" @update="handleSearchList"></addTempOffer>

    <!--日志-->
    <loger ref="loger"></loger>
  </div>
</template>

<script>

import {supplierListApi} from '@/api/allInLine/company'
import {
  getGoodsList,
  goodsSortSet,
  getFromCompanyList,
  warehouseList,
  goodsPricePublish,
  goodsDataSummary,
  salesmanList
} from '@/api/allInLine/inquiry'
import {getOrderUsersList} from '@/api/partner'
import {goodsSortList,getGoodsSnList,setEnableOrder} from '@/api/allInLine/goods'
import {goodsPriceList} from '@/api/allInLine/goodsApply'
import {formatDate} from '@/utils/date';
import addPurchaseOffer from './InquiryCom/addPurchaseOffer'
import addTempOffer from './InquiryCom/addTempOffer'
import loger from '@/views/allInLine/allInLineSale/InquiryCom/loger'
import store from '@/store'
import { mapGetters } from 'vuex'
import { Message } from 'element-ui';
// import addPumsGoods from './InquiryCom/addPumsGoods'

const defaultListQuery={
  pageNum: 1,
  pageSize: 10,
  categoryName:'', //品名
  goodsSnId:'', //牌号
  priceDate:[], //报价日期
  tab:'today',
  tab2:'charge',
  keywords:'' ,//商品、业务员模糊搜索
  warehouseName:'' ,//仓库名
  fromCompany:'', //供货方
  goodsName:'',
  goodsType:'',//商品类型(线上商品:normal)
  userId:'',
  chargeUserId:'',
  menuType : "all", //类型(今日已报价：todayPrice，今日未报价:todayUnPrice,线上商品：normal，线上商品未报价:normalUnPrice，所有:all)
  isEnableOrder:''
};
const defaultSendForm={
  goodsDetailId:'',
  fromCompany:'',
  warehouseName:'',
  stockNum:'',
  purchasePrice: '',
  costPrice: '',
  onlinePrice: '',//线上平台价
  validHours:'',//有效小时数
  sendDate:'',
  sendAreaId:'',
  payTypes:'',
  sendTypes:'',
  buyMinNum:'',
  priceType:'',
  priceRemark:'',
}
// const defaultSendForm2={
//   goodsId : '', //商品ID
//   inquirySort : '' //商品排序值
// }
export default {
  name: "index",
  data(){
    const validatePurchasePrice = (rules, value, callback) => {
      if (value > 999999 || value < 0) {
        callback(new Error('价格区间为0-999999'))
      } else {
        callback()
      }
    };
    const validateStockNum = (rules, value, callback) => {
      if (value > 99999 || value < 0) {
        callback(new Error('可售库存量区间为0-99999'))
      } else {
        callback()
      }
    };
     const validateHours = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('有效小时数不得小于0小时'))
      }
      callback()
    };
    return{
      // normalCount:0,
      // normalUnPriceCount:0,
      allCount:0,
      roles:store.getters.roles ? store.getters.roles : [],
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      minProfit:'',//最低毛利
      count:0,
      todayPriceCount:0,
      todayUnPriceCount:0,
      listLoading:false,
      sendForm:JSON.parse(JSON.stringify(defaultSendForm)),
      // sendForm2:JSON.parse(JSON.stringify(defaultSendForm2)),
      cutTime:new Date(new Date().setHours(0,0,0,0)).getTime() ,
      rules: {
        purchasePrice: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { validator: validatePurchasePrice,trigger: 'blur' },
        ],
        costPrice: [
          { required: true, message: '请输入采购成本价', trigger: 'blur' },
          { validator: validatePurchasePrice,trigger: 'blur' },
        ],
        onlinePrice: [
          { validator: validatePurchasePrice,trigger: 'blur' }
        ],
        validHours: [
          { required: true, message: "请输入有效小时数", trigger: "blur" },
          { validator:validateHours,trigger: "blur"}
        ],
        stockNum: [
          { required: true, message: '请输入可售库存量', trigger: 'blur' },
          { validator: validateStockNum, trigger: 'blur' },
        ],
        sendDate: [
          { required: true, message: '请选择发货日期', trigger: 'blur' }
        ]
      },
      isDisabled:{
          disabledDate(time) {
            // 设置日期限制 小于某个日期不能选择
            return time.getTime() < new Date().getTime() - 8.64e7;
          }
        },
      mindate:new Date(), //当前日期
      //sortList:[], //品名
      // rules2:{inquirySort:{required: true, message: '请填写排序值', trigger: 'blur'}},
      // dialogVisible2:false,
      materialsList:[],//牌号
      warehouseLists:[],//仓库
      chargeDataList:[],//负责人
      dialogVisible:false,
      btnLoading:false,
      loading:false,
      loading2:false,
      supplierList2:[],
      options:[],
      userOptionList:[],
      fromCompanyList:[],
      type:'todayPrice',
      records:[],
      gridOptions:{
        loading:this.listLoading,
        border: true,
        id: 'purchaseOffer',
        align:'center',
        autoResize:true,
        height:800,
        size:'mini',
        rowConfig: {
          keyField: 'pOId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        checkboxConfig:{
          reserve:true
        },
        toolbarConfig: {
          visible:false,
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },
        columns: [
           {
            field: 'goodsSn',
            fixed:'left',
            title: '品名牌号',
            width: 200,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'date',
            title: '日期',
            width: 100,
            slots: {
              // 使用插槽模板渲染
              default: 'num4_default',
            }
          },
          {
            field: 'purchasePrice',
            title: '价格',
            width: 100,
          },
          {
            field: 'fromCompany',
            title: '供货方',
            width: 200,
          },
          {
            field: 'costPrice',
            title: '采购成本价',
            width: 150,
          },
          {
            field: 'grossProfit',
            title: '采购吨毛利',
            width: 150,
          },
          {
            field: 'warehouseName',
            title: '发货仓库',
            width: 150,
          },
          {
            field: 'sendArea',
            title: '发货地',
            width: 150,
          },
          {
            field: 'stockNum',
            title: '可售库存量(吨)',
            width: 120,
          },
          {
            field: 'orderNum',
            title: '已下单(吨)',
            width: 120,
          },
          {
            field: 'remainNum',
            title: '剩余库存数量(吨)',
            width: 120,
          },
          {
            field: 'sapStockNum',
            title: '实际库存数量(吨)',
            width: 120,
          },
          {
            field: 'sendDate',
            title: '发货日期',
            width: 150,
          },
          {
            field: 'payTypes',
            title: '结算方式',
            width: 100,
          },
          {
            field: 'sendTypes',
            title: '发货方式',
            width: 100,
          },
          {
            field: 'goodsWeight',
            title: '包装(吨)',
            width: 120,
          },
          {
            field: 'buyMinNum',
            title: '起订量(吨)',
            width: 120,
          },
          {
            field: 'priceRemark',
            title: '备注',
            width: 150,
            showOverflow:true,
          },
          {
            field: 'minProfit',
            title: '最低毛利',
            width: 100,
          },
          {
            field: 'normProfit',
            title: '指导毛利',
            width: 100,
          },
          {
            field: 'userName',
            title: '采购员',
            width: 100,
          },
          {
            field: 'createdTime',
            title: '报价时间',
            width: 150,
          },
          {
            field: 'updatedTime',
            title: '更新时间',
            width: 150,
          },
        ],
        data:[{}],
      },

      btnloading1:false,
      btnloading2:false,

    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    todayPurchaseOffer() {
      if(this.roles.indexOf("todayPurchaseoffer") != -1){
        return true
      }else{
        return false
      }
    },
    myChargePurchaseOffer(){
      if(this.roles.indexOf("myChargePurchase0ffer") != -1){
        return true
      }else{
        return false
      }
    },
    allPurchaseOffer() {
      if(this.roles.indexOf("allPurchaseoffer") != -1){
        return true
      }else{
        return false
      }
    },
    purchaseOfferGoods() {
      if(this.roles.indexOf("purchaseofferGoods") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    this.getListData();
    this.getFromCompany()
    this.chargeData()
    // this.showTitle()
    // this.getGoodsSortList()
    // this.getMaterialsList()
  },
  components : {
    // addPumsGoods,
    addPurchaseOffer,
    addTempOffer,
    loger

  },
  filters: {
    formatTime(time) {
      if(time){
        let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd')
      } else {
        return ''
      }
    },
    fifterNumber(val1, val2) {
      let newval1 = val1 ? val1 : 0;
      let newval2 = val2 ? val2 : 0;
      return (newval1 - newval2).toFixed(2)
    }
  },
  methods:{
    changeMoreType(isEnableOrder){
      if (this.records.length <= 0) {
        this.$message.error("请勾选需要操作的记录");
        return false
      }
      if(isEnableOrder == 1){
        this.btnloading1 = true
      }else{
        this.btnloading2 = true
      }
      let data = {}
      let priceId = this.records.map(item=>item.priceId)
      data.priceId = priceId.join(",");
      data.isEnableOrder = isEnableOrder
      setEnableOrder(data).then(()=>{
        this.getListData()
        this.btnloading1 = false
        this.btnloading2 = false
        this.$message.success('操作成功！')
      })
    },
    changeOrderType(item,type){
      let data = {}
      data.priceId = item.priceId;
      if(type=='isEnableOrder'){
        data.isEnableOrder = item.isEnableOrder == 1 ? 0 : 1;
      }else if(type=='isMallGoodsSn'){
        data.isMallGoodsSn = item.isMallGoodsSn == 1 ? 0 : 1;
      }
      setEnableOrder(data).then(()=>{
        this.getListData()
        this.$message.success('操作成功！')
      })
    },
    checkboxChange(checked){
      this.records = JSON.parse(JSON.stringify(checked.records));
    },
    selectAllCheckboxChange(checked){
      this.records = JSON.parse(JSON.stringify(checked.records));
    },
    // 修改商品报价
    editPrice(item){
      this.dialogVisible = true
      this.minProfit = item.minProfit;
      for (let key in defaultSendForm) {
        this.sendForm[key]=item[key]?item[key]:defaultSendForm[key]
      }
    // this.sendForm.goodsDetailId = item.goodsDetailId?item.goodsDetailId:''
    // this.sendForm.fromCompany =item.fromCompany ?item.fromCompany:''
    // this.sendForm.warehouseName =item.warehouseName ?item.warehouseName:''
    // this.sendForm.sendAreaId =item.sendAreaId?item.sendAreaId:''
    // this.sendForm.payTypes =item.payTypes?item.payTypes:''
    // this.sendForm.sendTypes =item.sendTypes?item.sendTypes:''
    // this.sendForm.sendDate =item.sendDate?item.sendDate:''
    // this.sendForm.buyMinNum =item.buyMinNum?item.buyMinNum:''
    // this.sendForm.priceType =item.priceType? item.priceType :''
    // this.sendForm.priceRemark =item.priceRemark?item.priceRemark:''
    // this.sendForm.deliveryType =item.deliveryType?item.deliveryType:''
    // this.sendForm.stockNum = item.stockNum?item.stockNum:''
    // this.sendForm.purchasePrice = item.purchasePrice ? item.purchasePrice : ''
    },
    // 提交修改
    handleConfirm(){
      const data = JSON.parse(JSON.stringify(this.sendForm))
      this.$refs.sendForm.validate(valid=>{
      if(valid){
        this.btnLoading = true
        goodsPricePublish({goodsList:[data]}).then(res=>{
        Message.success('修改成功')
        if (this.sendForm.purchasePrice - this.sendForm.costPrice <= -200) {
          this.$alert('您的报价中存在毛利过低', '提示', {
            confirmButtonText: '关闭',
          });
        }
        this.btnLoading = false
        this.dialogVisible=false
        this.$refs.sendForm.resetFields()
        this.sendForm = JSON.parse(JSON.stringify(defaultSendForm))
        this.getListData()
      }).catch(err=>{
        this.btnLoading = false
      })
      }
      })
    },
    // 关闭修改窗口
    handleClose(){
      this.$refs.sendForm.resetFields()
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm))
      this.dialogVisible=false
    },
    // 提交修改
    // handleConfirm2(){
    //   goodsSortSet(this.sendForm2).then(res=>{
    //     Message.success('修改排序成功')
    //     this.dialogVisible2=false
    //     this.sendForm2 = JSON.parse(JSON.stringify(defaultSendForm2))
    //     this.handleSearchList()
    //   })
    // },
    // 关闭修改窗口
    // handleClose2(){
    //   this.dialogVisible2=false
    //   this.sendForm2 = JSON.parse(JSON.stringify(defaultSendForm2))
    // },
    toTemp(type){
      if(type == 'goods'){//批量报价
        if(this.records.length>0){
        this.$refs.addPurchaseOffer.showPop(this.records,type)
        }else{
          Message.error('请选择商品后报价')
        }
      } else if (type == 'create') { //批量复制报价
        if(this.records.length>0){
          this.records.forEach(item =>{
            item.createdTime = formatDate(new Date(item.createdTime), 'yyyy-MM-dd');
          })
          const bull =  this.records.every(item=>{
           return  (item.createdTime == this.records[0].createdTime ) && (item.createTimeSecond*1000 < this.cutTime)
          })
          if(bull){
          this.$refs.addPurchaseOffer.showPop(this.records,type)
          } else{
          Message.error('请勾选相同日期且非当日创建')
          }
        }else{
          Message.error('请勾选需要批量报价的商品')
        }

      }

    },
    //新增报价
    // addOffer(){
    //   this.$refs.addPurchaseOffer.showPop()
    // },
    //日志
    showLoger(item){
      this.$refs.loger.showPop6('goodsPrice',item)
    },
    // 编辑报价
    showAddGoods(item) {
      this.$refs.addTempOffer.showPop(item,'edit')
    },
    // 生成报价
    editTempOffer(item){
      this.$refs.addTempOffer.showPop(item,'add')
    },

    // 修改排序
    // editSort(row){
    //   this.dialogVisible2=true
    //   this.sendForm2.goodsId = row.goodsId
    //   this.sendForm2.inquirySort = row.inquirySort
    // },
    //删除报价
    delItem(item){
      this.$confirm('确认删除报价吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

      }).catch(() => {

      });
    },

    //获取供货方列表
    getFromCompany(){
      getFromCompanyList().then((res)=>{
        this.fromCompanyList = res;
      })
    },

    /**
     * 切换选择状态
     */
    async handleSelect(key, keyPath){
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery.tab = key;
      this.$refs.xGrid.clearCheckboxRow()
      this.records=[]
      if(key == 'create'|| key == 'all'){
          let now = new Date();
          let nowMonth = now.getMonth(); //当前月
          let nowYear = now.getFullYear(); //当前年

          //本月的开始时间
          let monthStartDate = new Date(nowYear, nowMonth, 1);
          //本月的结束时间
          let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
          let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
          let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
          let today = formatDate(now,'yyyy-MM-dd')
          this.listQuery.priceDate = [today,today];
      }
     await this.showTitle(key,'todayPrice')
     await this.handleSearchList();
    },

    handleSelect2(key, keyPath) {
      this.listQuery.tab2 = key;
      this.listQuery.chargeUserId = '';
      this.handleSearchList()
    },
    // 切换商品管理状态
    changeType(key) {
      this.type = key
      if(this.type != "all") {
        this.priceDate = []
      }
      this.listQuery.fromCompany = '';
      this.listQuery.warehouseName = '';
      this.listQuery.isEnableOrder = ''
      this.showTitle('goods',key)
      this.handleSearchList()
    },
    //变化字段显示
    showTitle(key,key2){
      if(key == 'today'){//今日报价
        this.gridOptions.columns= [
          {
            field: 'goodsSn',
            fixed:'left',
            title: '品名牌号',
            width: 200,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'date',
            title: '日期',
            width: 100,
            slots: {
              // 使用插槽模板渲染
              default: 'num4_default',
            }
          },
          {
            field: 'fromCompany',
            title: '供货方',
            width: 200,
          },
          {
            field: 'purchasePrice',
            title: '价格',
            width: 100,
          },
          {
            field: 'costPrice',
            title: '采购成本价',
            width: 150,
          },
          {
            field: 'grossProfit',
            title: '采购吨毛利',
            width: 150,
          },
          {
            field: 'warehouseName',
            title: '发货仓库',
            width: 150,
          },
          {
            field: 'sendArea',
            title: '发货地',
            width: 150,
          },
          {
            field: 'stockNum',
            title: '可售库存量(吨)',
            width: 120,
          },
          {
            field: 'orderNum',
            title: '已下单(吨)',
            width: 120,
          },
          {
            field: 'remainNum',
            title: '剩余库存数量(吨)',
            width: 120,
          },
          {
            field: 'sapStockNum',
            title: '实际库存数量(吨)',
            width: 120,
          },
          {
            field: 'sendDate',
            title: '发货日期',
            width: 150,
          },
          {
            field: 'payTypes',
            title: '结算条件',
            width: 100,
          },
          {
            field: 'sendTypes',
            title: '发货方式',
            width: 100,
          },
          {
            field: 'goodsWeight',
            title: '包装(吨)',
            width: 120,
          },
          {
            field: 'buyMinNum',
            title: '起订量(吨)',
            width: 120,
          },
          {
            field: 'priceRemark',
            title: '备注',
            width: 150,
            showOverflow:true,
          },
          {
            field: 'minProfit',
            title: '最低毛利',
            width: 100,
          },
          {
            field: 'normProfit',
            title: '指导毛利',
            width: 100,
          },
          {
            field: 'userName',
            title: '采购员',
            width: 100,
          },
          {
            field: 'createdTime',
            title: '报价时间',
            width: 150,
          },
          {
            field: 'updatedTime',
            title: '更新时间',
            width: 150,
          },
        ]
      }
      else if (key == 'create') {//我创建的
        this.gridOptions.columns = [
          {
            field: '',
            fixed:'left',
            title: '',
            width: 100,
            type:"checkbox"
          },
          {
            field: 'goodsSn',
            fixed:'left',
            title: '品名牌号',
            width: 200,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'date',
            title: '日期',
            width: 100,
            slots:{
            default:'num4_default'
            }
          },
          {
            field: 'purchasePrice',
            title: '价格',
            width: 100,
          },
          {
            field: 'fromCompany',
            title: '供货方',
            width: 200,
          },
          {
            field: 'costPrice',
            title: '采购成本价',
            width: 150,
          },
          {
            field: 'grossProfit',
            title: '采购吨毛利',
            width: 150,
          },
          {
            field: 'warehouseName',
            title: '发货仓库',
            width: 150,
          },
          {
            field: 'sendArea',
            title: '发货地',
            width: 150,
          },
          {
            field: 'stockNum',
            title: '可售库存量(吨)',
            width: 120,
          },
          {
            field: 'orderNum',
            title: '已下单(吨)',
            width: 120,
          },
          {
            field: 'remainNum',
            title: '剩余数量(吨)',
            width: 120,
          },
          {
            field: 'sapStockNum',
            title: '实际库存量(吨)',
            width: 120,
          },
          {
            field: 'sendDate',
            title: '发货日期',
            width: 150,
          },
          {
            field: 'payTypes',
            title: '结算条件',
            width: 100,
          },
          {
            field: 'sendTypes',
            title: '发货方式',
            width: 100,
          },
          {
            field: 'buyMinNum',
            title: '起订量(吨)',
            width: 120,
          },
          {
            field: 'priceRemark',
            title: '备注',
            width: 150,
          },

          {
            field: 'minProfit',
            title: '最低毛利',
            width: 100,
          },
          {
            field: 'normProfit',
            title: '指导毛利',
            width: 100,
          },

          {
            field: 'userName',
            title: '采购员',
            width: 100,
          },{
            field: 'createdTime',
            title: '报价时间',
            width: 150,
          },
          {
            field: 'updatedTime',
            title: '更新时间',
            width: 150,
          },
          {
            field: 'setting',
            title: '操作',
            width: 150,
            fixed:'right',
            slots:{
              default:'num3_default'
            }
          },
        ]
      }
      else if (key == 'all') {//全部报价
        this.gridOptions.columns = [
          {
            field: 'goodsSn',
            title: '品名牌号',
            fixed:'left',
            width: 200,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'purchasePrice',
            title: '价格',
            width: 100,
          },
          {
            field: 'fromCompany',
            title: '供货方',
            width: 200,
          },
           {
            field: 'costPrice',
            title: '采购成本价',
            width: 150,
          },
          {
            field: 'grossProfit',
            title: '采购吨毛利',
            width: 150,
          },
          {
            field: 'warehouseName',
            title: '发货仓库',
            width: 150,
          },
          {
            field: 'sendArea',
            title: '发货地',
            width: 150,
          },
          {
            field: 'stockNum',
            title: '可售库存量(吨)',
            width: 120,
          },
          {
            field: 'orderNum',
            title: '已下单(吨)',
            width: 120,
          },
          {
            field: 'remainNum',
            title: '剩余数量(吨)',
            width: 120,
          },
          {
            field: 'sapStockNum',
            title: '实际库存量(吨)',
            width: 120,
          },
          {
            field: 'sendDate',
            title: '发货日期',
            width: 100,
          },
          {
            field: 'payTypes',
            title: '结算条件',
            width: 100,
          },
          {
            field: 'sendTypes',
            title: '发货方式',
            width: 100,
          },
          {
            field: 'buyMinNum',
            title: '起订量(吨)',
            width: 120,
          },
          {
            field: 'priceRemark',
            title: '备注',
            width: 150,
          },


          {
            field: 'minProfit',
            title: '最低毛利',
            width: 100,
          },
          {
            field: 'normProfit',
            title: '指导毛利',
            width: 100,
          },
          {
            field: 'userName',
            title: '采购员',
            width: 100,
          },{
            field: 'createdTime',
            title: '报价时间',
            width: 150,
          },
          {
            field: 'updatedTime',
            title: '更新时间',
            width: 150,
          },
          {
            field: 'setting',
            title: '操作',
            width: 150,
            fixed:'right',
            slots:{
              default:'num3_default'
            }
          },
        ]
      }
      else if (key == 'goods' && key2 == 'todayPrice') {//商品管理 今日已报价
        this.gridOptions.columns = [
        {
            field: '',
            title: '',
            width: 100,
            type:'checkbox'
          },
          {
            field: 'goodsSn',
            title: '金蝶 牌号',
            width: 100,
          },
          {
            field: 'goodsName',
            title: '线上商品名称',
            width: 150,
          },
          {
            field: 'fromCompany',
            title: '供货方',
            width: 200,
          },
          {
            field: 'sendArea',
            title: '发货地',
            width: 150,
          },
          {
            field: 'sendTypes',
            title: '发货方式',
            width: 100,
          },
          {
            field: 'payTypes',
            title: '结算条件',
            width: 100,
          },
          {
            field: 'goodsWeight',
            title: '包装(吨)',
            width: 100,
          },
          {
            field: 'buyMinNum',
            title: '起订量(吨)',
            width: 120,
          },
          {
            field: 'goodsStock',
            title: '库存数量(吨)',
            width: 150,
          },
          {
            field: 'priceRemark',
            title: '备注',
            width: 100,
          },
          {
            field: 'minProfit',
            title: '最低毛利',
            width: 100,
          },
          {
            field: 'normProfit',
            title: '指导毛利',
            width: 100,
          },
          {
            field: 'purchasePrice',
            title: '采购底价',
            width: 100,
          },
          {
            field: 'priceTime',
            title: '当前报价时间',
            width: 150,
          },
          {
            field: 'inquirySort',
            title: '排序',
            width: 100,
          },
          {
            field: 'chargeUserName',
            title: '负责人',
            width: 100,
          }, {
            field: 'createUserName',
            title: '创建人',
            width: 100,
          },
          {
            field: 'setting',
            title: '操作',
            width: 230,
            fixed:'right',
            slots:{
              default:'num3_default'
            }
          },
        ]
      }
      else if (key == 'goods' && key2 == 'todayUnPrice') {//商品管理 今日未报价
        this.gridOptions.columns = [
        {
            field: '',
            title: '',
            width: 100,
            type:'checkbox'
          },
          {
            field: 'goodsSn',
            title: '金蝶 牌号',
            width: 100,
          },
          {
            field: 'goodsName',
            title: '线上商品名称',
            width: 150,
          },
          {
            field: 'goodsWeight',
            title: '包装(吨)',
            width: 100,
          },
          {
            field: 'buyMinNum',
            title: '起订量(吨)',
            width: 120,
          },
          {
            field: 'goodsStock',
            title: '库存数量(吨)',
            width: 150,
          },
          {
            field: 'priceRemark',
            title: '备注',
            width: 100,
          },
          {
            field: 'minProfit',
            title: '最低毛利',
            width: 100,
          },
          {
            field: 'normProfit',
            title: '指导毛利',
            width: 100,
          },
          {
            field: 'purchasePrice',
            title: '采购底价',
            width: 100,
          },
          {
            field: 'priceTime',
            title: '当前报价时间',
            width: 150,
          },
          {
            field: 'inquirySort',
            title: '排序',
            width: 100,
          },
          {
            field: 'chargeUserName',
            title: '负责人',
            width: 100,
          }, {
            field: 'createUserName',
            title: '创建人',
            width: 100,
          },
          {
            field: 'setting',
            title: '操作',
            width: 230,
            fixed:'right',
            slots:{
              default:'num3_default'
            }
          },
        ]
      }
    },

    //获取供应商列表
    remoteMethod3(query) {
      if(query && query!= ''){
        this.loading3 = true;
        //获取供应产列表
        supplierListApi({tab:this.listQuery.tab,supplierName:query,pageNum:1,pageSize:1000}).then(response => {
          this.supplierList2 = response.list;
          this.loading3 = false;
        }).catch(()=>{
          this.loading3 = false;
        });
      }
    },
    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getListData();
    },


    getGoodsDataSummary(){
      let data = JSON.parse(JSON.stringify(this.listQuery));
      const goodsData = {
          fromCompany:data.fromCompany,
          categoryName:data.categoryName,
          goodsSnId:data.goodsSnId,
          goodsName:data.goodsName,
          warehouseName:data.warehouseName,
          goodsType:data.goodsType,
          priceDate:data.priceDate,
          chargeUserId:data.chargeUserId,
          tab:data.tab2,
          menuType:this.type,
        }
      goodsDataSummary(goodsData).then(res=>{
          this.todayPriceCount = res.todayPriceCount
          this.todayUnPriceCount = res.todayUnPriceCount
          this.allCount = res.allCount
          // this.normalCount = res.normalCount
          // this.normalUnPriceCount = res.normalUnPriceCount
    })
    },
    //获取列表
    getListData(){
      this.getGoodsDataSummary()
      this.listLoading = true;
      let data = JSON.parse(JSON.stringify(this.listQuery));
      if(data.tab == 'goods'){
        const goodsData = {
          fromCompany:data.fromCompany,
          categoryName:data.categoryName,
          goodsSnId:data.goodsSnId,
          goodsName:data.goodsName,
          warehouseName:data.warehouseName,
          keywords:data.keywords,
          goodsType:data.goodsType,
          priceDate:data.priceDate,
          chargeUserId:data.chargeUserId,
          tab:data.tab2,
          menuType:this.type,
          isEnableOrder:data.isEnableOrder,
          pageSize:data.pageSize,
          pageNum:data.pageNum,
        }
        getGoodsList(goodsData).then(res=>{
          this.gridOptions.data = res.list;
          this.count = res.count;
          this.listLoading = false;
        }).catch(()=>{
        this.listLoading = false;
      })
      }else{
        const pmsData = {
          keywords:data.keywords,
          tab:data.tab,
          categoryName:data.categoryName,
          fromCompany:data.fromCompany,
          goodsSnId:data.goodsSnId,
          userId:data.userId,
          priceDate:data.priceDate,
          pageNum:data.pageNum,
          pageSize:data.pageSize,
        }
        goodsPriceList(pmsData).then((res)=>{
        this.gridOptions.data = res.list;
        this.count = res.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      })
      }

    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.$refs.xGrid.clearCheckboxRow()
      this.records=[]
      this.getListData();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.$refs.xGrid.clearCheckboxRow()
      this.records=[]
      this.getListData();
    },
    // 品名
    // getGoodsSortList(){
    //     goodsSortList().then(res=>{
    //   this.sortList = res
    // })
    // },
     // 牌号
    getMaterialsList(queryString){
      getGoodsSnList({keywords:queryString}).then(res=>{
        this.materialsList = res
      })

    },
    // 获取仓库名称
    handleWarehouseId(val){
      warehouseList({fromCompany:val}).then(res=>{
        this.warehouseLists=res.list
      })
    },

    chargeData(){
      getOrderUsersList().then(res=>{
        this.chargeDataList = res
      })
    }
  },
}
</script>

<style scoped lang="scss">

</style>
